<template>
    <div>
        <div class="title">{{ route.query.id ? '编辑账号' : '新增账号' }}</div>
        <div v-if="!route.query.id">
            <el-button style="height:30px;width: 60px;" @click="() => { router.push('/') }">返回</el-button>
            <el-button style="height:30px;width: 60px;" :color="falg ? '#409eff' : ''" @click="fn(true)">商
                户</el-button>
            <el-button style="height:30px;width: 60px;" :color="falg ? '' : '#409eff'" @click="fn(false)">派出所</el-button>
        </div>
        <div style="margin-top: 10px;" v-if=falg>
            <el-form :model="form" :rules="rules" ref="ruleFormRef">
                <el-form-item label="商户类型" prop="category" :inline="true">
                    <el-select v-model="form.category" class="m-2" placeholder="请选择商户类型" size="large">
                        <el-option v-for="item in merchantType" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="选择联防" prop="pid">
                    <el-select v-model="form.pid" class="m-2" placeholder="请选择派出所" size="large" @change="communityList">
                        <el-option v-for="item in defense" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="商户名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入商户名称" style="width:220px;height: 35px;" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="商户位置" prop="city">
                        <el-cascader v-model="form.city" :options="cityList" @change="handleChange" placeholder="请选择地区"
                            :props="{ value: 'value' }" ref="citycascader" disabled />
                    </el-form-item>
                    <el-form-item prop="community_id" :inline="true">
                        <el-select v-model="form.community_id" placeholder="请选择联防社区">
                            <el-option v-for="item in fromStore.defenseCommunity" :key="item.id" :label="item.name"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item prop="location" :inline="true">
                        <el-autocomplete v-model="form.location" :fetch-suggestions="querySearch" clearable
                            class="inline-input w-50" placeholder="请输入详细地址" @select="handleSelect" @input="mapRetrieval" />
                    </el-form-item>
                </div>
                <el-form-item label="">
                    <div class="map">
                        <baidu-map id="bmap" class="baidumap" style="overflow:auto" :center="mapCenter" :dragging="false"
                            :zoom="scale" scroll-wheel-zoom @ready="fn1">
                            <bm-marker :position="marker" animation="BMAP_ANIMATION_BOUNCE">
                            </bm-marker>
                        </baidu-map>
                    </div>
                </el-form-item>
                <el-form-item label="选择状态" prop="status">
                    <el-select v-model="form.status" placeholder="选择状态" size="large">
                        <el-option v-for="item in state" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="route.query.id">
                    <el-button @click="() => { router.push('/') }">取消</el-button>
                    <el-button type="primary" @click="editSubmit(ruleFormRef)">提交</el-button>
                </el-form-item>
                <el-form-item v-else="route.query.id">
                    <el-button @click="() => { router.push('/') }">取消</el-button>
                    <el-button type="primary" @click="onSubmit(ruleFormRef)">下一步</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div v-else="flag">
            <el-form :model="policeForm" ref="formRef" style="margin-top: 10px;">
                <el-form-item label="派出所名称" prop="name" :rules="{
                    required: true,
                    message: '请输入派出所名称',
                    trigger: 'blur'
                }">
                    <el-input v-model="policeForm.name" placeholder="派出所名称" style="width:220px;height: 35px;" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="派出所位置" prop="region_code" :rules="{
                        required: true,
                        message: '请选择区域',
                        trigger: 'blur'
                    }">
                        <el-cascader v-model="policeForm.region_code" :options="cityList" @change="handleChange"
                            placeholder="请选择区域" :props="{ value: 'value' }" ref="citycascader" />
                    </el-form-item>
                    <el-form-item prop="location" :rules="{
                        required: true,
                        message: '请选择商户类型',
                        trigger: 'blur'
                    }">
                        <el-autocomplete v-model="policeForm.location" :fetch-suggestions="querySearch" clearable
                            class="inline-input w-50" placeholder="请输入详细地址或派出所名称" @select="handleSelect"
                            style="width: 300px;" @input="mapRetrieval" />
                    </el-form-item>
                </div>
                <el-form-item label=" ">
                    <div class="map">
                        <baidu-map id="bmap" class="baidumap" style="overflow:auto" :center="mapCenter" :dragging="false"
                            :zoom="scale" scroll-wheel-zoom @ready="fn1">
                            <bm-marker :position="marker" animation="BMAP_ANIMATION_BOUNCE">
                            </bm-marker>
                        </baidu-map>
                    </div>
                </el-form-item>
                <el-form-item label="选择状态" prop="status" :rules="{
                    required: true,
                    message: '请选择商户类型',
                    trigger: 'blur'
                }">
                    <el-select v-model="policeForm.status" class="m-2" placeholder="选择状态" size="large">
                        <el-option v-for="item in state" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <div v-for="(item, i) in policeForm.communities" style="display: flex;" :key="i">
                    <el-form-item label="管辖社区" :prop="'communities.' + [i] + '.name'" :rules="{
                        required: true,
                        message: '请输入辖区名',
                        trigger: 'blur',
                    }">
                        <el-input v-model="item.name" placeholder="管辖社区" style="width:220px;height: 35px;" />
                    </el-form-item>
                    <el-form-item label="额定摄像头" :prop="'communities.' + [i] + '.rated'" :rules="{
                        required: true,
                        message: '请输入额定摄像头数量',
                        trigger: 'blur',
                    }" style="margin-left: 25px;">
                        <el-input v-model.number="item.rated" placeholder="额定摄像头" style="width:220px;height: 35px;" />
                        <el-button type="primary" @click="fn2(i)">{{ i === 0 ? '增加' : '删除' }}</el-button>
                    </el-form-item>
                </div>
                <el-form-item v-if="route.query.id">
                    <el-button @click="() => { router.push('/') }">取消</el-button>
                    <el-button type="primary" @click="editSubmit(formRef)">提交</el-button>
                </el-form-item>
                <el-form-item v-else="route.query.id">
                    <el-button @click="() => { router.push('/') }">取消</el-button>
                    <el-button type="primary" @click="onSubmit(formRef)">下一步</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted } from 'vue'
import { cityList } from './ciytdata/cityList'
import { useRouter, useRoute } from 'vue-router';
import { getCity, getSearchAddress, getCommunityList, getUseDetails, setUserDetails, setUserPolice } from '../../api/index'
import { useAddDataStore } from '../../store/useAddDataStore'
import type { FormInstance, } from 'element-plus'
import { ElMessage } from 'element-plus'
// import { BaiduMap } from 'vue-baidu-map-3x'

let fromStore = useAddDataStore()
let cityData = ref([])
const router = useRouter()
const route = useRoute()
const scale = ref<number>(13)  //map缩放比例
const falg = ref<boolean>(true)
const mapCenter = ref<any>({ lng: 116.404, lat: 39.915 })
const citycascader = ref()
const defense = ref()
const editData = ref<any>({})
const ruleFormRef = ref<FormInstance>()
const formRef = ref<FormInstance>()
const marker = ref<any>({ lng: 116.404, lat: 39.915 })
const markerTitle = ref("北京")
const fn = (bol: boolean) => {
    fromStore.business = bol
    falg.value = bol
}
const fn1 = () => {
    if (falg.value) {
        marker.value = {
            lng: 0,
            lat: 0
        }
        mapCenter.value = { lng: fromStore.from.point.lng, lat: fromStore.from.point.lat }//fromStore.from.point
        marker.value = { lng: fromStore.from.point.lng, lat: fromStore.from.point.lat }//fromStore.from.point
    } else {
        marker.value = {
            lng: 0,
            lat: 0
        }
        console.log('加载了');

        mapCenter.value = { lng: fromStore.policeForm.point.lng, lat: fromStore.policeForm.point.lat }//fromStore.from.point
        marker.value = { lng: fromStore.policeForm.point.lng, lat: fromStore.policeForm.point.lat }//fromStore.from.point
    }


}

const fn2 = (i: number) => {
    if (i === 0) {
        policeForm.value.communities.push({
            name: '',
            rated: null,
            id: 0,
        })
    } else {
        policeForm.value.communities.splice(i, 1)
    }
}
interface RestaurantItem {
    value: string
    point: object
}
interface communities {
    name: string
    id: number
    rated: number | null
}
interface form {
    category: number | null
    pid: string
    name: string
    status: number | null
    community_id: number | null
    city: any[]
    location: string
    point: object
}
interface policeForm {
    category: number
    region_code: string | any[]
    name: string
    status: number | null
    location: string
    point: object
    communities: communities[]
}


const policeForm = ref<policeForm>({
    category: 0,
    region_code: [],
    name: '',
    status: null,
    location: '',
    point: {},
    communities: [{
        name: '',
        id: 0,
        rated: null
    }]
})

const form = ref<form>({
    category: null,
    pid: '',
    name: '',
    status: null,
    community_id: null,
    city: [],
    location: '',
    point: {}
})
const rules = ref({
    category: [
        {
            required: true,
            message: '请选择商户类型',
            trigger: 'blur'
        },
    ],
    pid: [
        {
            required: true,
            message: '请选择派出所',
            trigger: 'blur'
        },
    ],
    status: [
        {
            required: true,
            message: '选择状态',
            trigger: 'blur'
        },
    ],
    name: [
        {
            required: true,
            message: '请输入商户名称',
            trigger: 'blur'
        },
    ],
    community_id: [
        { required: true, message: '请选择联防社区', trigger: 'blur' },
    ],
    city: [
        { required: true, message: '请选择地区', trigger: 'blur' },
    ],
    location: [
        { required: true, message: '请输入详细地址', trigger: 'blur' },
    ],
})

// 地图检索参数
const data = ref({
    query: '',
    region: ''
})

//获取社区列表
const communityList = async (val: number) => {

    let res = await getCommunityList({ identify_id: val })
    console.log(res);

    fromStore.defenseCommunity = res.data.data
    let region_code: string = ''
    defense.value.forEach((item: any) => {
        if (item.id === val) {
            region_code = item.region_code
        }
    })

    let num = region_code.slice(0, 3)
    let num1 = region_code.slice(0, 4)
    let num2 = region_code
    if (num === '110' || num === '120' || num === '310' || num === '500') {
        form.value.city = [num + '000', num2]
    } else {
        form.value.city = [num + '000', num1 + '00', num2]
    }
    // mapCenter
}



//获取联防列表
const defenseList = async () => {
    let res = await getCity({ category: 0 })
    if (res.data.code === 0 && res.data.data.records) {
        defense.value = res.data.data.records
        data.value.region = res.data.data.records[0].region

    }
}



// 获取地图检索联想
const mapRetrieval = async (val: any) => {
    data.value.query = val
    let res = await getSearchAddress(data.value)
    if (res.data.data) {
        cityData.value = res.data.data.map((item: any) => {
            return { value: item.name, point: item.point }
        })
        var point = res.data.data[0].point
        marker.value = { lng: point.lng, lat: point.lat }
        markerTitle.value = res.data.data[0].address
        console.log('地图检索');

        mapCenter.value = { lng: point.lng, lat: point.lat }
        form.value.point = res.data.data[0].point
        policeForm.value.point = res.data.data[0].point
        scale.value = 20
    }
    restaurants.value = loadAll()
}
//autocomplete组件的数据
const restaurants = ref<RestaurantItem[]>([])
// autocomplete组件的方法
const querySearch = (queryString: string, cb: any) => {
    const results = loadAll()
    cb(results)
}
//autocomplete组件的数据
const loadAll = () => {
    return cityData.value
}
//autocomplete组件选择触发
const handleSelect = (item: RestaurantItem) => {
    form.value.point = item.point
    policeForm.value.point = item.point
}
// 城市级联选中后触发
const handleChange = async (value: any) => {
    policeForm.value.region_code = value.pop()
    data.value.region = citycascader.value.inputValue.split("/").map((item: any) => item.trim()).join('')
    var point = citycascader.value.inputValue.split("/").map((item: any) => item.trim()).join('')
    mapCenter.value = point
    fromStore.region = citycascader.value.inputValue.split("/").map((item: any) => item.trim()).join('')

}

const merchantType = [
    {
        value: 1,
        label: '社区',
    },
    {
        value: 3,
        label: '学校',
    },
    {
        value: 5,
        label: '酒店',
    },

    {
        value: 9,
        label: '工厂',
    },
    {
        value: 7,
        label: 'KTV',
    },
]
const state = [{
    label: '启用',
    value: 1,
}, {
    label: '禁用',
    value: 2,
}]
const editSubmit = async (formEl: any) => {
    fromStore.backFlag = false
    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            if (route.query.id) {
                if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {
                    editData.value = {
                        ...editData.value,
                        ...policeForm.value
                    }
                    editData.value.region_code = editData.value.region_code.pop()
                    let res = await setUserPolice(editData.value)
                    if (res.data.code === 0) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        router.push('/')
                    } else {
                        ElMessage.error(res.data.message)
                    }
                } else {
                    editData.value = {
                        ...editData.value,
                        ...form.value
                    }
                    delete editData.value.city
                    let res = await setUserDetails(editData.value)
                    console.log(res);

                    if (res.data.code === 0) {
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        router.push('/')
                    } else {
                        ElMessage.error({ message: res.data.message })
                    }
                }
            }
        } else {
            ElMessage.error('格式有误，请仔细查验后再提交')
        }
    })
}
// 下一步
const onSubmit = async (formEl: any) => {
    fromStore.backFlag = false
    if (!formEl) return
    await formEl.validate(async (valid: any, fields: any) => {
        if (valid) {
            fromStore.from = form.value
            fromStore.policeForm = policeForm.value

            router.push('/aiconfig')
        } else {
            ElMessage.error('格式有误，请仔细查验后再提交')
        }
    })

}


onMounted(async () => {
    falg.value = fromStore.business
    defenseList()
    // restaurants.value = loadAll()
    //判断是否是返回
    if (fromStore.backFlag) {

        if (fromStore.business) {
            form.value = fromStore.from
            scale.value = 20
        } else {
            policeForm.value = fromStore.policeForm
            scale.value = 20
        }
    }
    //判断是否为编辑
    if (route.query.id) {

        let res = (await getUseDetails({ id: route.query.id })).data.data
        //判断编辑的是派出所还是商户
        if (Number(route.query.category) === 0 || Number(route.query.category) === 2) {

            falg.value = false
            policeForm.value.name = res.name
            policeForm.value.location = res.location
            policeForm.value.point = res.point
            policeForm.value.status = res.status
            policeForm.value.communities = res.communities.map((item: any) => {
                return {
                    name: item.name,
                    id: item.id,
                    rated: item.camera_rated
                }
            })
            data.value.region = res.region
            let num = res.region_code.slice(0, 3)
            let num1 = res.region_code.slice(0, 4)
            let num2 = res.region_code
            if (num === '110' || num === '120' || num === '310' || num === '500') {
                policeForm.value.region_code = [num + '000', num2]
            } else {
                policeForm.value.region_code = [num + '000', num1 + '00', num2]
            }
            mapCenter.value = res.point
            marker.value = res.point
            editData.value = {
                communities: res.communities,
                contact: {
                    phone: res.Administrator.phone,
                    real_name: res.Administrator.real_name,
                    remark: res.Administrator.remark,
                    username: res.Administrator.username,

                },
                id: res.id,
                pid: res.pid,
                permission_codes: res.PermissionCodes
            }
        } else {
            fromStore.from.point = res.point
            form.value.name = res.name
            form.value.category = res.category
            form.value.pid = res.pid
            form.value.community_id = res.Community.id
            form.value.location = res.location
            form.value.status = res.status
            form.value.point = res.point
            let res1 = await getCommunityList({ identify_id: res.pid })
            fromStore.defenseCommunity = res1.data.data
            let num = res.region_code.slice(0, 3)
            let num1 = res.region_code.slice(0, 4)
            let num2 = res.region_code
            if (num === '110' || num === '120' || num === '310' || num === '500') {
                form.value.city = [num + '000', num2]
            } else {
                form.value.city = [num + '000', num1 + '00', num2]
            }
            editData.value = {
                contact: {
                    phone: res.Administrator.phone,
                    real_name: res.Administrator.real_name,
                    remark: res.Administrator.remark,
                    username: res.Administrator.username,
                },
                id: Number(route.query.id),
                permission_codes: res.PermissionCodes,
                region_code: res.region_code,

            }
        }
    }
})
</script>
<style scoped lang='less'>
.title {
    height: 30px;
    line-height: 25px;
    border-bottom: 1px solid #ddd;
    margin-bottom: 10px;
}

.map {
    width: 45%;
    height: 500px;
}

.baidumap {
    width: 100%;
    height: 100%;

    /deep/ .anchorBL {
        display: none !important;
    }

}
</style>